<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        
        <TableHeader
            :buttons="['comSearch', 'columnDisplay']"
            :quick-search-placeholder="t('quick Search Placeholder', { fields: t('tz.quick Search Fields') })"
        >
        <el-button v-blur class="table-header-operate" type="primary" @click="handleAdd" :disabled="selectedItems.length==0">
            <span class="table-header-operate-text" >生成{{menu.label}}对账单</span>
        </el-button>
        <el-button v-blur class="table-header-operate" type="primary" @click="handleDel" :disabled="selectedItems.length==0">
            <span class="table-header-operate-text" >删除对账单费用</span>
        </el-button>
        <el-button v-blur class="table-header-operate" type="primary" @click="handleInsert" :disabled="selectedItems.length==0">
            <span class="table-header-operate-text">加入{{menu.label}}对账单</span>
        </el-button>
        <div style="margin-left:16px;" v-if="selectedItems.length">
            <span>合计应收人民币(元)：{{ state.rmb }}</span><br/>
            <span>合计应收美元(美元)：{{ state.usd }}</span> <span style="margin-left:30px">合计折合人民币(元)：{{ state.zhRmb }}</span> 
        </div>
        </TableHeader>
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" >
            <template #columnPrepend>
                <el-table-column  type="expand">
                    <template #default="props">
                        <el-table :data="props.row.two" :border="false">
                            <el-table-column width="100">
                            </el-table-column>
                            <el-table-column width="60" label="选择">
                                <template #default="scope">
                                    <el-checkbox
                                        v-model="scope.row.selected"
                                        :disabled="scope.row.JOBNO"
                                        @change="handleSubClick(props.row)"
                                        ></el-checkbox
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column label="对账单号" prop="MARKNO" />
                            <el-table-column label="JOB NO" prop="JOBNO" />
                            <!-- <el-table-column label="费用类型" prop="ITEMCODE" /> -->
                            <el-table-column label="往来单位" prop="CORPCODE" />
                            <el-table-column label="费用项目" prop="ITEMCODE" />
                            <el-table-column label="币别" prop="MONEYTYPE" />
                            <el-table-column label="金额" prop="MONEY" />
                            <el-table-column label="税率" prop="TAXRATE" />
                            <el-table-column label="数量" prop="ROW_NUMBER" />
                            <el-table-column label="计价单位" prop="PRICETYPE" />
                            <el-table-column label="费率" prop="RATIO" />
                            <el-table-column label="对账人" prop="DZOP" />
                            <el-table-column label="对账单日期" prop="DZDATE" />
                            <el-table-column label="JOB单制作人" prop="JOBOP" />
                            <el-table-column label="JOB单日期" prop="JOBDATE" />
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column width="60" label="选择">
                    <template #default="scope">
                        <el-checkbox
                            v-model="scope.row.selected"
                            :indeterminate="scope.row.indeterminate"
                            @change="handleMainClick(scope.row)"
                            ></el-checkbox
                        >
                    </template>
                </el-table-column>
            </template>
        </Table>
        <el-dialog
        class="result-dialog"
        :close-on-click-modal="false"
        :title="dialog.title"
        :model-value="dialog.show"
        @close="baTable.toggleForm();handleClose()"
        destroy-on-close

        :width="dialog.type == 'insert'?980:500"
        >
            <section v-if="dialog.type=='add_err'">
                <h4>{{ dialog.content }}</h4>
                <div v-if="dialog.result&&dialog.result.length" style="margin: 20px 0;padding: 10px 20px;border: 1px solid #ddd;border-radius: 4px;min-height: 100px;">
                    {{ dialog.result.join(',') }}
                </div>
            </section>
            <section v-if="dialog.type=='add'">
                <div>请输入{{menu.label}}对账单子年月：
                    <el-date-picker
                        v-model="dialog.select"
                        type="month"
                        value-format="YYYYMM"
                        placeholder="选择年月"
                        />
                </div>
                <div style="margin-top:20px">当前有{{ selectedItems.length }}票费用即将生成应收对账单号，确认是否生成{{menu.label}}对账单？</div>
            </section>
            <section v-if="dialog.type=='del'">
                <h4>{{ dialog.content }}</h4>
            </section>
            <section v-if="dialog.type == 'insert'">
                <el-form :inline="true" :model="dialog.insertTable.form" class="demo-form-inline">
                    <el-form-item label="托运人">
                        <el-input v-model="dialog.insertTable.form.SENDER" placeholder="请输入" :disabled="true"/>
                    </el-form-item>
                    <el-form-item label="通用查询">
                        <el-input v-model="dialog.insertTable.form.quick_search" placeholder="请输入" />
                    </el-form-item >
                    <el-form-item label="应收对账单号">
                        <el-input v-model="dialog.insertTable.form.DZDNO" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="对账时间">
                        <el-date-picker
                        v-model="dialog.insertTable.form.DZDATE"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="Start date"
                        end-placeholder="End date"
                        :value-format="'YYYY-MM-DD HH:mm:ss'"
                        />
                    </el-form-item>
                    <el-form-item>
                    <el-button type="primary" @click="handleInsert">Query</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="dialog.insertTable.data" style="width: 100%" :height="400">
                    <el-table-column prop="DZDNO" label="应收对账单号" width="140" />
                    <el-table-column prop="RMB" label="人民币金额（元）" align="right" />
                    <el-table-column prop="USD" label="美元金额（美元）" align="right"/>
                    <el-table-column prop="ZHRMB" label="折算人民币（元）" align="right"/>
                    <el-table-column prop="DZOP" label="对账人" width="80"/>
                    <el-table-column prop="DZDATE" label="对账时间" />
                    <el-table-column label="操作" >
                        <template #default="scope">
                            <el-button type="primary" @click="confirmInsert(scope.row)">选择</el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </section>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialog.show = false">退出</el-button>
                    <el-button v-if="dialog.type=='add'" type="primary" :disabled="!dialog.select" @click="confirmAdd">确认</el-button>
                    <el-button v-if="dialog.type=='del'" type="primary" @click="confirmDel">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted ,computed, watchEffect, reactive, inject} from 'vue'
import baTableClass from '/@/utils/baTable'
import { tz } from '/@/api/controllerUrls'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
// import PopupTabs from './PopupTabs.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import createAxios from '/@/utils/axios'
import bill from '../bill/index.vue'

const { t } = useI18n()
const tableRef = ref()
const optButtons = defaultOptButtons(["edit","delete"])
const baTable = new baTableClass(
    new baTableApi(tz,'_dz'),
    {
        pk: 'TZID',
        column: [
            // { type: 'selection', align: 'center', operator: false },
            { label: t('tz.TZID'), prop: 'TZID', align: 'center',operator:false},
            { label: t('tz.SENDER'), prop: 'SENDER', align: 'center' 
            },
            { label: t('tz.GOODSC'), prop: 'GOODSC', align: 'center' },
            { label: '箱号', prop: 'CNTRNO', align: 'center' },
            { label: t('tz.PORTLOAD'), prop: 'PORTLOAD', align: 'center' },
            { label: t('tz.PORTDIS'), prop: 'PORTDIS', align: 'center' },
            { label: '应收人民币', prop: 'RMB', align: 'center' },
            { label: '应收美金', prop: 'USD', align: 'center' },
            { label: '实际装货时间', prop: 'ZHDATE', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: '实际卸货时间', prop: 'SHDATE', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: t('tz.SALER'), prop: 'SALER', align: 'center' },
            { label: t('tz.SALERDEPT'), prop: 'SALERDEPT', align: 'center' },
            { label: '来往单位', prop: 'CORPCODE', align: 'center',show:false},

            { label: '对账状态', prop: 'BILLSTATUS', align: 'center',show:false,comSearchRender: 'select',
                replaceValue: { '未对账': '未对账', '已对账': '已对账'},
            },
            { label: '币别', prop: 'MONEYTYPE', align: 'center',show:false,comSearchRender: 'select',
                replaceValue: { 'RMB': '人民币','USD':'美元' }
            },
            { label: '费用类型', prop: 'BILLCLASS', align: 'center',show:false,comSearchRender: 'select',
                replaceValue: { '正常&代垫':'正常&代垫','更正':'更正' }
            },
            { label: '费用项目', prop: 'ITEMCODE', align: 'center',show:false,
                comSearchRender: 'remoteSelect', remote: {
                pk: 'code',
                field: 'codename',
                remoteUrl: 'admin/codelib/'  + 'now?where=itemcode',
                params: {}}
            },
            { label: '对账单号', prop: 'MARKNO', align: 'center',show:false},
            { label: '税率', prop: 'TAXRATE', align: 'center',show:false,
                comSearchRender: 'remoteSelect', remote: {
                pk: 'code',
                field: 'codename',
                remoteUrl: 'admin/codelib/'  + 'now?where=taxrate',
                params: {}}
            },
            { label: '所属JOB', prop: 'JOBNO', align: 'center',show:false},
        ],
        dblClickNotEditColumn: [undefined, ],
        defaultOrder: { prop: 'TZID', order: 'desc' },
        showComSearch:true
    },
    {
        defaultItems: [],
    },
    {
        getIndex:() =>{
            return true
            if(baTable.comSearch.form.SENDER){
                return true
            }else{
                ElMessage({
                    message:'请输入托运人',
                    type:'error'
                })
                return false
            }
        },
        onTableAction:(obj)=>{
            console.log(obj)
            // return false
        },
        onTableDblclick:(table:any)=>{
            return false
        }
    }
)

provide('baTable', baTable)
const menu:any = inject('menu')
const dialog = reactive({
    show:false,
    loading:false,
    type:'add_err', //生成错误  add 生成成功 
    title:'',
    content:'',
    result:[],
    select:'',
    insertTable:{
        form:{
            SENDER:'',
            quick_search:'',
            DZDNO:'',
            DZDATE:[],
        },
        data:[],
        page:1,
        total:0,
    }
})

const state = reactive({
    rmb:0,
    usd:0,
    zhRmb:0
})


onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.table.filter!.type = menu.type
    baTable.comSearch.form.BILLSTATUS = '未对账'
    baTable.comSearch.form.BILLCLASS = '正常&代垫'
    // baTable.getIndex()?.then(() => {
    //     baTable.initSort()
    //     baTable.dragSort()
    // })
})

const selectedItems = computed(()=>{
    let arry:any = []
    state.rmb = 0
    state.usd = 0
    state.zhRmb = 0
    baTable.table.data?.map((item:any)=>{
        if(item.two&&item.two.length){
            item.two.map((it:any)=>{
                if(it.selected){
                    arry.push(it)
                    if(it.MONEYTYPE == 'RMB'){
                        state.rmb += Number(it.MONEY)
                    }else{
                        state.usd += Number(it.MONEY)
                        state.zhRmb += Number(it.ZHRMB||0)
                    }
                }
            })
        }
    })

    return arry
})


const handleSubClick = (mainItem:any)=>{
    let checkedList = []
    mainItem.two.map((it:any)=>{
        if(it.selected) checkedList.push(it)
    })
    mainItem.selected = (checkedList.length>0&&checkedList.length==mainItem.two.length)?true:false
    mainItem.indeterminate = (checkedList.length>0&&checkedList.length<mainItem.two.length)?true:false
}


const handleMainClick = (item:any)=>{
    let bl = item.selected
    item.indeterminate = false
    item.two.forEach((it:any)=>{
        if(!it.JOBNO) it.selected=bl
    })
}

const handleClose = ()=>{
    dialog.result = []
    dialog.type = ''
    dialog.title = ''
    dialog.content = ''
    dialog.select = ''
    dialog.insertTable = {
        form:{
            SENDER:'',
            quick_search:'',
            DZDNO:'',
            DZDATE:[],
        },
        data:[],
        page:1,
        total:0,
    }
}

const handleAdd = ()=>{
    console.log(selectedItems.value)
    dialog.show = true
    dialog.title = '生成'+menu.label +'对账单'
    dialog.result = []
    createAxios({
        url:'admin/dzd/generate_xy',
        params:{
            BILLID:selectedItems.value.map((item:any)=>item.BILLID),
            type:menu.type
        },
        method:'get',
    }).then((res:any)=>{
        dialog.show = true
        dialog.type = 'add'
        dialog.select = ''
    }).catch((err:any)=>{
        if(err.data.length){
            dialog.type = 'add_err'
            dialog.content = `创建对账单失败，当前有${err.data.length}票业务的费用未审核，请审核后再生成对账单。`
            dialog.result = err.data
        }else{
            dialog.type = 'add_err'
            dialog.content = err.msg
        }
    })
}

const confirmAdd = ()=>{
    createAxios({
        url:'admin/dzd/generate',
        method:'get',
        params:{
            ny:dialog.select,
            BILLID:selectedItems.value.map((item:any)=>item.BILLID),
        }
    }).then((res:any)=>{
        dialog.show = false
        baTable.getIndex()
        ElMessage({
            message:'生成对账单成功！',
            type:'success'
        })
    })
}

const handleDel = ()=>{
    createAxios({
        url:'admin/bill/dele_xy',
        params:{
            BILLID:selectedItems.value.map((item:any)=>item.BILLID),
            type:menu.type
        },
        method:'get',
    }).then((res:any)=>{
        dialog.show = true
        dialog.type = 'del'
        dialog.title = '删除'+menu.label +'对账单'
        dialog.content = res.msg
    })
}

const confirmDel = ()=>{
    createAxios({
        url:'admin/bill/dele_dz',
        params:{
            BILLID:selectedItems.value.map((item:any)=>item.BILLID),
            type:menu.type
        },
        method:'get',
    }).then(()=>{
        dialog.show = false
        baTable.getIndex()
        ElMessage({
            message:'删除成功！',
            type:'success'
        })

    })
}

const handleInsert = ()=>{
    dialog.show = true
    dialog.loading = true
    dialog.title = '选择对账单'
    dialog.insertTable.form.SENDER = baTable.comSearch.form.SENDER
    let search = []
    if(dialog.insertTable.form.DZDNO) search.push({"field":"DZDNO","val":dialog.insertTable.form.DZDNO,"operator":"="})
    if(dialog.insertTable.form.DZDATE&&dialog.insertTable.form.DZDATE.length) search.push({"field":"DZDATE","val":dialog.insertTable.form.DZDATE.join(','),"operator":"="})
    createAxios({
        url:'admin/dzd/index',
        params:{
            type:menu.type,
            search:search.length?search:undefined,
            quick_search:dialog.insertTable.form.quick_search?dialog.insertTable.form.quick_search:undefined
        },
        method:'get',
    }).then((res:any)=>{
        dialog.type = 'insert'
        dialog.insertTable.data = res.data.list

        console.log(res)
    })
}

const confirmInsert = (item:any)=>{
    createAxios({
        url:'admin/bill/add_dz',
        params:{
            BILLID:selectedItems.value.map((item:any)=>item.BILLID),
            MARKNO:item.DZDNO
        },
        method:'get',
    }).then((res:any)=>{
        dialog.show = false
        baTable.getIndex()
        ElMessage({
            message:'加入对账单成功！',
            type:'success'
        })
    })
}


</script>

<script lang="ts">
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus'
import menu from '/@/lang/pages/en/auth/menu'
export default defineComponent({
    name: 'tz',
})
</script>

<style scoped lang="scss">
.result-dialog{
    section{
        padding: 20px 30px;
    }
}
</style>
